const Router = require('koa-router');

const router = new Router({
	prefix:'/api'
});

const AppInfo = require('../mongodb/db.js');

router.get('/',async(ctx,next)=>{
	await ctx.render('index',{
		title:"首页"
	})
});
router.get('/add_info_api',async(ctx,next)=>{
	await ctx.render('addInfo',{
		title:"添加页"
	})
});
router.post('/add_info_api',async(ctx,next)=>{
	var postData = ctx.request.body;
	var Info =new AppInfo(postData);
	try{
		await Info.save();
    ctx.body = "success";
	} catch(e){
		console.log(e);
    ctx.body = "error";
	}
});
//获取所有文章按时间-----最新
router.get('/get_all_info_time',async(ctx,next)=>{
	var allInfo;
	await AppInfo.find({}).sort({time : -1}).exec(function(err,data){
		if (err){
			console.log(err);
		}
		allInfo = data;
		console.log(data);
	});
	ctx.body = allInfo;
});
//获取所有文章按likeNum数-----最热
router.get('/get_all_info_like',async(ctx,next)=>{
	var allInfo;
	await AppInfo.find({}).sort({like : -1}).exec(function(err,data){
		if (err){
			console.log(err);
		}
		allInfo = data;
		console.log(data);
	});
	ctx.body = allInfo;
});
//传id查询
router.get('/get_info_byId',async(ctx,next)=>{
  var postData = ctx.request.query;
  var id = postData.id;
	var allInfo;
	await AppInfo.find({_id:id},function(err,data){
		if (err){
			console.log(err);
		}
		allInfo = data;
		console.log(data);
	});
	ctx.body = allInfo;
});
//修改是否喜欢
router.get('/edit_like_num',async(ctx,next)=>{
  var postData = ctx.request.query;
  var id = postData.id;
  //var id= "590c3b68e0946b31849aba54";
  var userId = postData.userId;
  //var userId = "postData.name";
  var likedList = [];
	var islike;
	var likeNum;
	console.log(userId);
  await AppInfo.findById(id,function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
            Info = res;
            likedList = Info.liked;
						console.log(likedList);
						var indexPos = likedList.indexOf(userId);
						if(indexPos==-1){
							likedList.push(userId);
							islike = true;
						} else{
							likedList.splice(indexPos,1);
							islike = false;
						};
						console.log(likedList);
						likeNum = likedList.length;
        }
  });
	//修改likeNum
	console.log("likeNum"+likeNum)
	var updatalikeNum = {'like':likeNum};
  await AppInfo.findByIdAndUpdate(id,updatalikeNum,function(err,data){
    if (err){
      console.log(err);
    }
    console.log('likeNum change success');
  });
  //更新喜欢数值
  var updataData = {'liked':likedList};
	var allInfo;
	await AppInfo.findByIdAndUpdate(id,updataData,function(err,data){
		if (err){
			console.log(err);
		}
    console.log('likedList change success');
	});
  ctx.status = 200;
  ctx.body = islike;
});
//新加评论
router.get('/edit_mark',async(ctx,next)=>{
    var postData = ctx.request.query;
    console.log(postData)
    var id = postData.id;
    var userId = postData.userId;
    var userName = postData.userName;
    var markContent = postData.content;
    var userIcon = postData.userIcon;
    var markList
    await AppInfo.findById(id,function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
            Info = res;
            markList = Info.markList
        }
    });
  var markInfo = {};
  markInfo.userName = userName;
	markInfo.userId = userId;
  markInfo.markContent = markContent;
	markInfo.userIcon = userIcon;
  markList.push(markInfo);
 //修改markNum
  var markNum = markList.length;
  var updataMarkNum = {'mark':markNum};
  await AppInfo.findByIdAndUpdate(id,updataMarkNum,function(err,data){
    if (err){
      console.log(err);
    }
    console.log('success');
  });
  //插入值
  var updataData = {'markList':markList};
	var allInfo;
	await AppInfo.findByIdAndUpdate(id,updataData,function(err,data){
		if (err){
			console.log(err);
		}
    console.log('success');
	});
  ctx.status = 200;
  ctx.body = "success";
});
//查看所有评论
router.get('/get_content_list',async(ctx,next)=>{
  var postData = ctx.request.query;
  var id = postData.id;
  var MarkList=[];
  await AppInfo.findById(id,function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
            MarkList = res.markList;
        }
  });
  ctx.status = 200;
  ctx.body = MarkList;
});
//查看我喜欢的
router.get('/get_like_content',async(ctx,next)=>{
  var postData = ctx.request.query;
  var userId = postData.id;
  var likedList=[];
  await AppInfo.find({},function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
            InfoList = res
        }
  });
  InfoList.forEach(function(item){
    item.liked.forEach(function(name){
      if(name == userId){
        likedList.push(item);
      }
    });
  })
  ctx.status = 200;
  ctx.body = likedList;
});
//查看我评论的
router.get('/get_mark_content',async(ctx,next)=>{
  var postData = ctx.request.query;
  var userId = postData.id;
  var markedList=[];
	console.log(userId);
  await AppInfo.find({},function(err, res){
        if (err) {
            console.log("Error:" + err);
        }
        else {
            InfoList = res;
        }
   });
	 InfoList.forEach(function(item){
			 item.markList.forEach(function(mark){
				  console.log(mark)
				 for(var key in mark){
					 if(key=='userId'){
						 if(mark['userId'] == userId){
							 markedList.push(item);
							 console.log(item)
						 }
					 }
				 };
			 })
		});
   ctx.status = 200;
   ctx.body = markedList;
});
module.exports = router;
